package com.ruoyi.web.controller.system;

import java.net.URI;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.CommonMethod;
import com.ruoyi.common.utils.DecodeUtils;
import com.ruoyi.common.utils.RedisClient;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.TourismUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TourismUser;
import com.ruoyi.system.service.ITourismUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户Controller
 *
 * @author gqd
 * @date 2020-12-26
 */
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/system/tourismuser")
public class TourismUserController extends BaseController
{
    @Autowired
    private ITourismUserService tourismUserService;
    @Autowired
    private TokenService tokenService;
    @Resource
    private TourismUserMapper tourismUserMapper;
    @Resource
    private CommonMethod commonMethod;
    @Resource
    private DecodeUtils decodeUtils;
    @Resource
    private RedisClient redisClient;

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:tourismuser:list')")
    @GetMapping("/list")
    public TableDataInfo list(TourismUser tourismUser)
    {
        startPage();
        List<TourismUser> list = tourismUserService.selectTourismUserList(tourismUser);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:tourismuser:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TourismUser tourismUser)
    {
        List<TourismUser> list = tourismUserService.selectTourismUserList(tourismUser);
        ExcelUtil<TourismUser> util = new ExcelUtil<TourismUser>(TourismUser.class);
        return util.exportExcel(list, "tourismuser");
    }

    /**
     * 获取用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:tourismuser:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(tourismUserService.selectTourismUserById(id));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:tourismuser:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TourismUser tourismUser)
    {
        return toAjax(tourismUserService.insertTourismUser(tourismUser));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:tourismuser:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TourismUser tourismUser)
    {
        return toAjax(tourismUserService.updateTourismUser(tourismUser));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:tourismuser:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(tourismUserService.deleteTourismUserByIds(ids));
    }

    /**
     * 用户登录
     * @param map
     * @return
     */
    @PostMapping("/weiLogin")
    public AjaxResult userLogin(@RequestBody Map map){
        AjaxResult ajaxResult =new AjaxResult();
        String avatarUrl = (String) map.get("avatarUrl");
        String nickName = (String) map.get("nickName");
        Integer sex = (Integer) map.get("sex");
        String code = (String) map.get("code");
        try {
            log.info("进入微信登录实现方法----------------->");
            String sexs = sex + "";
            // 创建Httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String resultString = "";
            CloseableHttpResponse response = null;
            String url="https://api.weixin.qq.com/sns/jscode2session?appid=wxa93a692dcaf9650b&secret=513e450c81ef35bc4017c22fbe67b7e8&js_code="+code+"&grant_type=authorization_code";
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            // 解析json
            JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
            String sessionKeys = jsonObject.get("session_key").toString();
            log.info("sessionKey-------"+sessionKeys);
            String openId = jsonObject.get("openid").toString();
            //校验openId是否有效
            if (StringUtils.isBlank(openId) || StringUtils.isBlank(sessionKeys)) {
                return AjaxResult.error("微信登录失败！");
            }
            //以unionId去查是否存在用户,如果存在修改用户信息并返回
            TourismUser tourismUser = tourismUserMapper.selectUserByOpenId(openId);
            if (tourismUser != null) {
                tourismUser.setSessionKey(sessionKeys);
                tourismUserMapper.updateTourismUser(tourismUser);
                //设置token
                log.info("====="+tourismUser.getId());
                LoginUser loginUser = new LoginUser();
                loginUser.setUserId(tourismUser.getId());
                SysUser sysUser = new SysUser();
                sysUser.setUserName("测试");
                sysUser.setPassword("测试");
                loginUser.setUser(sysUser);
                String token =  tokenService.createToken(loginUser);
                ajaxResult.put("code",202);
                ajaxResult.put("resultCode", "1000");
                ajaxResult.put("resultMsg", "微信登录成功");
                ajaxResult.put("token", token);
                ajaxResult.put("openId", tourismUser.getTourismId());
                return ajaxResult;
            }else{
                TourismUser tourismUser1 = new TourismUser();
                tourismUser1.setNickName(nickName);
                tourismUser1.setUserPhoto(avatarUrl);
                tourismUser1.setUserSex(sexs);
                tourismUser1.setTourismId(openId);
                tourismUser1.setSessionKey(sessionKeys);
                //新增用户信息
                if (1 == tourismUserMapper.insertTourismUser(tourismUser1)) {
                    log.info("插入用户成功------------>");
                    System.out.println("拿到userId----------------------->"+tourismUser1.getId());
                    //设置token
                    LoginUser loginUser = new LoginUser();
                    loginUser.setUserId(tourismUser1.getId());
                    SysUser sysUser = new SysUser();
                    sysUser.setUserName("测试");
                    sysUser.setPassword("测试");
                    loginUser.setUser(sysUser);
                    String token =  tokenService.createToken(loginUser);
                    System.out.println("成功生成token-------------->"+token);
                    ajaxResult.put("code",202);
                    ajaxResult.put("resultCode", "1000");
                    ajaxResult.put("resultMsg", "微信登录成功");
                    ajaxResult.put("token", token);
                    ajaxResult.put("openId", tourismUser1.getTourismId());
                    return ajaxResult;
                } else {
                    return AjaxResult.error("微信登录失败,请稍后重试");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("微信登录失败,请稍后重试");
        }

    }

    /**
     * 解析手机号
     * @param map
     * @return
     */
    @PostMapping("/decodePhone")
    public AjaxResult decodePhone(@RequestBody Map map){
        AjaxResult ajaxResult =new AjaxResult();
        String encryptedData = (String) map.get("encryptedData");
        String iv = (String) map.get("iv");
        String userId = (String) map.get("userId");
        System.out.println(userId+"openId");
        log.info("进入解密手机号实现方法------------->");
        try {
            //通过userId获取用户信息用于解密手机号
            TourismUser tourismUser = tourismUserMapper.selectUserByOpenId(userId);
            if (null == tourismUser) {
                return AjaxResult.error("用户信息错误,请稍后重试");
            }
            if (StringUtils.isNotBlank(tourismUser.getUserPhone())) {
                //以userId作为redisKey存入redis并设置有效时间为半小时
                redisClient.set(tourismUser.getTourismId(), tourismUser.getUserPhone(), 1800);
                ajaxResult.put("Msg", "获取用户手机号成功");
                ajaxResult.put("code",200);
                return ajaxResult;
            }
            String sessionKey = tourismUser.getSessionKey();
            //log.info("用于解密的sessionKey-------------->" + sessionKey);
            System.out.println("用于解密的sessionKey-------------->" + sessionKey);
            //解密获得手机号
            JSONObject decrypt = decodeUtils.decrypt(encryptedData, iv, sessionKey);
            String phone = decrypt.getString("phoneNumber");
            System.out.println(phone);

            if (StringUtils.isNotEmpty(phone)) {
                tourismUser.setUserPhone(phone);
                log.info("用户手机号为--------->" + phone);
                //插入用户手机号
                if (1 == tourismUserMapper.updateTourismUser(tourismUser)) {
                    log.info("插入用户手机号成功----------->");
                } else {
                    log.error("插入用户手机号失败----------->");
                }
                redisClient.set(tourismUser.getTourismId(), phone, 1800);
                ajaxResult.put("Msg", "获取用户手机号成功");
                ajaxResult.put("code",200);
                return ajaxResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("用户获取手机号失败！");
    }

    /**
     * 通过userId查询用户的信息
     * @param
     * @return
     */
    @PostMapping("/selectUserByUserId")
    public AjaxResult selectUserByUserId(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser == null) {
            return AjaxResult.error(201, "您还未注册或者登录，请先注册或登录");
        } else {
            TourismUser tourismUser = tourismUserMapper.selectByUserId(loginUser.getUserId());
            if (tourismUser == null || loginUser.getUserId() == null) {
                return AjaxResult.error(201, "您还未注册或者登录，请先注册或登录");
            }
            return AjaxResult.success(tourismUser);
        }
    }



    @PostMapping("/getToken")
    public AjaxResult getToken(){
        AjaxResult ajax = AjaxResult.success();
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(11);
        SysUser sysUser = new SysUser();
        sysUser.setUserName("测试");
        sysUser.setPassword("测试");
        loginUser.setUser(sysUser);
        String token =  tokenService.createToken(loginUser);
        ajax.put("token",token);
        return ajax;
    }

    @PostMapping("/getUserToken")
    public AjaxResult getUserToken(HttpServletRequest request){
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(loginUser != null){
            System.out.println(loginUser.getUserId());
            TourismUser tourismUser = tourismUserService.selectTourismUserById(loginUser.getUserId());
            if(tourismUser != null){
                return AjaxResult.success(tourismUser);
            }
        }
        System.out.println();
        return AjaxResult.error("token 有误");
    }
}
